//
//  BXHomeViewController.m
//  cangoe
//
//  Created by 魏延(颜魏) on 2025/2/18.
//

#import "BXHomeViewController.h"
#import "BxBleTableViewCell.h"
#import "BTManager.h"
#import "DeviceListViewController.h"
#import "CustomCircleView.h"
#import "HomeViewController.h"

@interface BXHomeViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UIView *socBgView;
@property (nonatomic, strong) CustomCircleView *circleView;

@property (weak, nonatomic) IBOutlet UILabel *socLabel;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UILabel *voltageLabe;
@property (weak, nonatomic) IBOutlet UILabel *currentLabel;
@property (weak, nonatomic) IBOutlet UILabel *capcityLabel;

@property (weak, nonatomic) IBOutlet UIView *singleBatteryView;
@property (weak, nonatomic) IBOutlet UIView *parallelView;

@property (weak, nonatomic) IBOutlet UILabel *tabTitleLabel;
@property (weak, nonatomic) IBOutlet UITableView *bleTab;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bleTabHeight;

@property (weak, nonatomic) IBOutlet UICollectionView *dcCollect;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *dcCollectHeight;

@property (weak, nonatomic) IBOutlet UILabel *maxTempLabel;
@property (weak, nonatomic) IBOutlet UILabel *minTempLabel;
@property (weak, nonatomic) IBOutlet UILabel *maxSingleVLabel;
@property (weak, nonatomic) IBOutlet UILabel *minSingleVLabel;

@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *bleList;
@property (nonatomic, strong) NSMutableArray *bleDataList;

@property (nonatomic, assign) BOOL isShow;
@property (nonatomic, assign) BOOL isStartQuery;

@end

@implementation BXHomeViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.bleList = [[NSMutableArray alloc] init];
    self.bleDataList = [[NSMutableArray alloc] init];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevice:) name:kBTSearchDevices object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getBatteryLevel:) name:kBTGetBatteryLevel object:nil];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
    [self.singleBatteryView addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap2:)];
    [self.parallelView addGestureRecognizer:tap1];
//    self.parallelView.layer.borderWidth = 1;
//    self.parallelView.layer.borderColor = SUBJECT_COLOR.CGColor;
// 
//    self.tabTitleLabel.userInteractionEnabled = YES;
//    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap1:)];
//    [self.tabTitleLabel addGestureRecognizer:tap1];


    [self.bleTab registerNib:[UINib nibWithNibName:@"BxBleTableViewCell" bundle:nil] forCellReuseIdentifier:@"BxBleTableViewCell"];
    [self.dcCollect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    
    self.circleView = [[CustomCircleView alloc] initWithFrame:CGRectMake(0 , 0, 195, 195)];
    [self.socBgView addSubview:self.circleView];
    
    [[BTManager sharedBTManager] startScan];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.isShow = YES;
    if ([BTManager sharedBTManager].isGettingBattery != self.isStartQuery) {
        [BTManager sharedBTManager].isGettingBattery = self.isStartQuery;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.isShow = NO;
    [[BTManager sharedBTManager] stopScan];
//    [BTManager sharedBTManager].isGettingBattery = NO;
}

- (void)searchDevice:(NSNotification *)nf {
    if (!self.isShow) {
        return;
    }
    NSArray<CBPeripheral *> *list = nf.object;
    NSString *uuidStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"HXBleUUIDList"];
    NSArray *uuids = [uuidStr componentsSeparatedByString:@"[-@-]"];
    if (!uuids.count) {
        return;
    }
    [self.bleList removeAllObjects];
    for (NSString *uuid in uuids) {
        for (CBPeripheral *p in list) {
            if ([p.identifier.UUIDString isEqualToString:uuid]) {
                [self.bleList addObject:p];
                break;
            }
        }
    }
    self.bleTabHeight.constant = 40 * self.bleList.count;
    [self.bleTab reloadData];
    [BTManager sharedBTManager].lookSocBlues = self.bleList;
    if ([BTManager sharedBTManager].lookSocBlues != [BTManager sharedBTManager].batteryLevelSource) {
        if ([BTManager sharedBTManager].isGettingBattery != self.isStartQuery) {
            [BTManager sharedBTManager].isGettingBattery = self.isStartQuery;
        }
    }
}

- (void)getBatteryLevel:(NSNotification *)nf {
    [self.bleDataList removeAllObjects];
    for (NSDictionary *dict in [BTManager sharedBTManager].batteryLevelSource) {
        if ([[dict objectForKey:@"batteryLevel"] integerValue] >= 0) {
            [self.bleDataList addObject:dict];
        }
    }
    self.dcCollectHeight.constant = (NSInteger)((self.bleDataList.count + 3) / 4) * 40;
    [self.bleTab reloadData];
    [self.dcCollect reloadData];
    [self updateUI];
}

- (void)updateUI {
    NSInteger soc = 0;
    CGFloat voltage = 0;
    CGFloat current = 0;
    CGFloat capcity = 0;
    NSInteger count = 0;
    CGFloat maxTemp = 0;
    CGFloat minTemp = 1000;
    CGFloat maxV = 0;
    CGFloat minV = 1000;
    NSInteger maxVIndex = 0;
    NSInteger minVIndex = 1000;
    NSString *maxTempName = @"";
    NSString *minTempName = @"";
    NSString *maxVName = @"";
    NSString *minVName = @"";
    BOOL isDischarging = NO;
    BOOL isStanding = NO;
    for (NSDictionary *dict in self.bleDataList) {
        if ([[dict objectForKey:@"batteryLevel"] integerValue] >= 0) {
            count ++;
            soc += [[dict objectForKey:@"soc"] integerValue];
            voltage += [[dict objectForKey:@"voltage"] floatValue];
            capcity += [[dict objectForKey:@"capcity"] floatValue];
            if ([[dict objectForKey:@"maxTemp"] floatValue] > maxTemp) {
                maxTemp = [[dict objectForKey:@"maxTemp"] floatValue];
                maxTempName = [dict objectForKey:@"name"];
            }
            if ([[dict objectForKey:@"minTemp"] floatValue] < minTemp) {
                minTemp = [[dict objectForKey:@"minTemp"] floatValue];
                minTempName = [dict objectForKey:@"name"];
            }
            if ([[dict objectForKey:@"maxV"] floatValue] > maxV) {
                maxV = [[dict objectForKey:@"maxV"] floatValue];
                maxVIndex = [[dict objectForKey:@"maxIndex"] integerValue];
                maxVName = [dict objectForKey:@"name"];
            }
            if ([[dict objectForKey:@"minV"] floatValue] < minV) {
                minV = [[dict objectForKey:@"minV"] floatValue];
                minVIndex = [[dict objectForKey:@"minIndex"] integerValue];
                minVName = [dict objectForKey:@"name"];
            }
            isDischarging = [[dict objectForKey:@"dischargeC"] floatValue] > 0;
            if ([[dict objectForKey:@"dischargeC"] floatValue] == 0 && [[dict objectForKey:@"chargeC"] floatValue] == 0) {
                isStanding = YES;
            }
            if ([[dict objectForKey:@"chargeC"] floatValue] > 0) {
                current += [[dict objectForKey:@"chargeC"] floatValue];
            }else if ([[dict objectForKey:@"dischargeC"] floatValue] > 0) {
                current += [[dict objectForKey:@"dischargeC"] floatValue];
            }
        }
    }
    voltage = voltage / count;
    soc = soc / count;
    if (count == 0) {
        return;
    }
    
    self.circleView.rate = (NSInteger)soc;
    [self.circleView startAnimation];
    self.socLabel.text = @((NSInteger)soc).description;
    self.voltageLabe.text = [NSString stringWithFormat:@"%.1fV", voltage];
    self.currentLabel.text = [NSString stringWithFormat:@"%.1fA", current];
    self.capcityLabel.text = [NSString stringWithFormat:@"%.1fAh", capcity];
    self.statusLabel.text = isDischarging ? @"disCharging" : isStanding ? @"standing" : @"Charging";
    self.maxTempLabel.text = [NSString stringWithFormat:@"%.1f°C | %@", maxTemp, maxTempName];
    self.minTempLabel.text = [NSString stringWithFormat:@"%.1f°C | %@", minTemp, minTempName];
    self.maxSingleVLabel.text = [NSString stringWithFormat:@"%.2fV | %ldS | %@", maxV, maxVIndex, maxVName];
    self.minSingleVLabel.text = [NSString stringWithFormat:@"%.2fV | %ldS | %@", minV, minVIndex, minVName];
}

- (void)handleTap:(UITapGestureRecognizer *)tap {
//    self.singleBatteryView.layer.borderWidth = 1;
//    self.singleBatteryView.layer.borderColor = SUBJECT_COLOR.CGColor;
    self.isStartQuery = NO;
    [BTManager sharedBTManager].isGettingBattery = self.isStartQuery;
    self.parallelView.layer.borderWidth = 1;
    self.parallelView.layer.borderColor = self.isStartQuery ? SUBJECT_COLOR.CGColor : [UIColor clearColor].CGColor;
    HomeViewController *vc = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
//    [self.navigationController popViewControllerAnimated:YES];
}

- (void)handleTap2:(UITapGestureRecognizer *)tap {
    self.isStartQuery = !self.isStartQuery;
    self.parallelView.layer.borderWidth = 1;
    self.parallelView.layer.borderColor = self.isStartQuery ? SUBJECT_COLOR.CGColor : [UIColor clearColor].CGColor;
    [BTManager sharedBTManager].isGettingBattery = self.isStartQuery;
    
    self.singleBatteryView.layer.borderWidth = 1;
    self.singleBatteryView.layer.borderColor = [UIColor clearColor].CGColor;
}

- (IBAction)actionBle:(id)sender {
    [self handleTap1:nil];
}

- (void)handleTap1:(UITapGestureRecognizer *)tap {
//    if (self.isStartQuery) {
//        self.isStartQuery = NO;
//        self.parallelView.layer.borderWidth = 1;
//        self.parallelView.layer.borderColor = self.isStartQuery ? SUBJECT_COLOR.CGColor : [UIColor clearColor].CGColor;
//        [BTManager sharedBTManager].isGettingBattery = self.isStartQuery;
//    }

    DeviceListViewController *vc = [[DeviceListViewController alloc] initWithNibName:@"DeviceListViewController" bundle:nil];
    vc.isDXHomeIn = YES;
    WeakSelf
    vc.clickItemBlock = ^(CBPeripheral * _Nonnull peripheral) {
        BOOL isAdded = NO;
        for (CBPeripheral *p in weakSelf.bleList) {
            if ([p.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
                isAdded = YES;
                break;
            }
        }
        if (!isAdded) {
            [weakSelf.bleList addObject:peripheral];
            weakSelf.bleTabHeight.constant = 40 * weakSelf.bleList.count;
            [weakSelf.bleTab reloadData];
            [BTManager sharedBTManager].lookSocBlues = weakSelf.bleList;
            if ([BTManager sharedBTManager].lookSocBlues != [BTManager sharedBTManager].batteryLevelSource) {
                [BTManager sharedBTManager].isGettingBattery = self.isStartQuery;
            }
            [weakSelf saveBleList];
        }
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)saveBleList {
    NSMutableArray *uuids = [[NSMutableArray alloc] init];
    for (CBPeripheral *p in self.bleList) {
        [uuids addObject:p.identifier.UUIDString];
    }
    [[NSUserDefaults standardUserDefaults] setObject:[uuids componentsJoinedByString:@"[-@-]"] forKey:@"HXBleUUIDList"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.bleList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BxBleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BxBleTableViewCell"];
    cell.index = @(indexPath.row + 1).description;
    cell.name = self.bleList[indexPath.row].name;
    NSString *voltage = @"0";
    NSString *soc = @"0";
    if (self.bleDataList.count) {
        for (NSDictionary *dict in self.bleDataList) {
            if ([[dict objectForKey:@"name"] isEqualToString:cell.name] && [[dict objectForKey:@"batteryLevel"] integerValue] >= 0) {
                voltage = [NSString stringWithFormat:@"%.1f", [[dict objectForKey:@"voltage"] floatValue]];
                soc = [dict objectForKey:@"soc"];
                break;
            }
        }
    }
    cell.voltage = voltage;
    cell.soc = soc;
    WeakSelf
    cell.clickDelete = ^{
        NSString *name = weakSelf.bleList[indexPath.row].name;
        [weakSelf.bleList removeObjectAtIndex:indexPath.row];
        weakSelf.bleTabHeight.constant = 40 * weakSelf.bleList.count;
        [BTManager sharedBTManager].lookSocBlues = weakSelf.bleList;
        for (NSInteger i=0; i<[BTManager sharedBTManager].batteryLevelSource.count; i++) {
            NSDictionary *dict = [BTManager sharedBTManager].batteryLevelSource[i];
            if ([[dict objectForKey:@"name"] isEqualToString:name]) {
                [[BTManager sharedBTManager].batteryLevelSource removeObject:dict];
            }
        }
        [weakSelf getBatteryLevel:nil];
        [weakSelf saveBleList];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = 0;
    [UIPasteboard generalPasteboard].string = @"";
    NSString *ct = [UIPasteboard generalPasteboard].string;
    for (NSDictionary *dict in self.bleDataList) {
        NSInteger dc = [[dict objectForKey:@"dc"] integerValue];
        BOOL state = ((dc >> 1) & 0x01) > 0;
        if (state) {
            count += 1;
        }
    }
    [UIPasteboard generalPasteboard].string = ct;
    return count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
   
//    NSInteger count = 0;
//    NSInteger index = 0;
//    for (NSDictionary *dict in self.bleDataList) {
//        index += 1;
//        NSInteger dc = [[dict objectForKey:@"dc"] integerValue];
//        BOOL state = ((dc >> 1) & 0x01) > 0;
//        if (state) {
//            count += 1;
//        }
//        if (count == indexPath.row) {
//            break;
//        }
//    }
//    NSDictionary *dataDict = self.bleDataList[index - 1];
    
    NSMutableArray *list = [NSMutableArray array];
    for (CBPeripheral *p in self.bleList) {
        for (NSDictionary *dict in self.bleDataList) {
            if ([[dict objectForKey:@"name"] isEqualToString:p.name]) {
                NSInteger dc = [[dict objectForKey:@"dc"] integerValue];
                BOOL state = ((dc >> 1) & 0x01) > 0;
                if (state) {
                    [list addObject:dict];
                    break;
                }
            }
        }
    }
    NSDictionary *dataDict = list[indexPath.item];
    NSInteger index = 0;
    for (CBPeripheral *p in self.bleList) {
        index += 1;
        if ([[dataDict objectForKey:@"name"] isEqualToString:p.name]) {
            break;
        }
    }

    UILabel *statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    statusLabel.textColor = [UIColor lightGrayColor];
    statusLabel.font = [UIFont systemFontOfSize:14];
    statusLabel.text = [NSString stringWithFormat:@"%ld %@", index, ([[dataDict objectForKey:@"dc"] integerValue] % 2) == 1 ? @"ON" : @"OFF"];
    [cell.contentView addSubview:statusLabel];
    
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(40, 11, 34, 18)];
//    iv.image = [UIImage imageNamed:([[dataDict objectForKey:@"dc"] integerValue] % 2) == 1 ? @"sw_on" : @"sw_off"];
    iv.layer.cornerRadius = 9;
    iv.layer.masksToBounds = YES;
    iv.backgroundColor = ([[dataDict objectForKey:@"dc"] integerValue] % 2) == 1 ? RGB16(0xFF2D00) : RGB16(0xa3a3a3);
    [cell.contentView addSubview:iv];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kWidth - 68) / 4, 40);
}


@end
